<script>
import {dictionaryRequest} from "../../../util/js/globalRequestJs";
import {deleteNotice, searchData, updateStatus} from "./noticeListJs";
import {blurElement, formatDate, gradeElement} from "../../../util/js/utils";
import EditNotice from "./dialog/EditNotice.vue"

export default {
  name: "NoticeList",
  components: {
    'edit-dialog': EditNotice
  },
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      isDialogVisible: false,

      search: {
        priority: '',
        releaseTime: [],
        type: '',
        status: '0',
        title: '',
        pageSize: 5,
        currentPage: 1
      },

      types: [],
      statuses: [],
      totalNumber: 0,
      rowData: {}
    }
  },
  mounted() {
    this.getDictionary();
    this.searchNotice();
  },
  methods: {
    formatDate,
    // 获取选中数据行
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(newSize) {
      this.search.pageSize = newSize;
      this.searchNotice();
    },
    handleCurrentChange(newPage) {
      this.search.currentPage = newPage;
      this.searchNotice();
    },
    // 搜索
    searchNotice() {
      const _this = this;
      const data = _this.search;
      searchData(data).then(res => {
        if (res.code === '200') {
          // 判断公告是否过期
          _this.tableData = _this.ifExpire(res.data.data);
          _this.totalNumber = res.data.totalNumber;
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(error => {
        _this.$router.push('/framework/error')
        console.log(error);
      })
    },
    // 判断公告是否过期
    ifExpire(data) {
      // 获取当前时间
      var currentTime = new Date().getTime();
      // 创建一个新的数组来存储已过期并且状态不是"已过期"的数据
      let newData = [];
      let ids = [];
      data.forEach(item => {
        var deadlineTime = new Date(item.deadline).getTime();
        // 比较时间戳
        if (currentTime >= deadlineTime && item.status !== '已过期') {
          // 已过期且状态不是已过期
          // 保存id
          ids.push(item.nuuid);
        } else {
          // 返回原始数据项
          newData.push({...item})
        }
      });
      if (ids.length > 0) {
        updateStatus(ids,'2').then(res => {
          if (res.code === '200') {
          } else {
            this.$router.push('/framework/error')
          }
        }).catch(err => {
          this.$router.push('/framework/error')
        })
      }
      return newData;
    },
    // 清空搜索项
    clearSearch() {
      this.search.priority = '';
      this.search.releaseTime = [];
      this.search.type = '';
      this.search.status = '0';
      this.search.title = '';
      // 刷新数据
      this.searchNotice();
    },
    // 获取类型数据选项
    getDictionary() {
      const _this = this;
      dictionaryRequest('notice', 'type').then(res => {
        if (res.code === '200') {
          this.types = res.data;
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(error => {
        _this.$router.push('/framework/error');
        console.log(error);
      })
      dictionaryRequest('notice', 'status').then(res => {
        if (res.code === '200') {
          this.statuses = res.data;
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(error => {
        _this.$router.push('/framework/error');
        console.log(error);
      })
    },
    // 删除
    deleteNotice(row) {
      const _this = this;
      // 如果是undefined，则表示为批量删除，如果不是则是单行删除
      let ids = []
      if (row === undefined) {
        // 先判断是否选中数据行
        if (_this.multipleSelection.length === 0) {
          _this.$message.warning("您未选中数据！")
          return;
        }
        // 选中则提取出所有的id
        ids = _this.multipleSelection.map(row => row.nuuid);
      } else {
        ids.push(row.nuuid);
      }
      // 发送删除请求，确认是否确定删除
      _this.$confirm('是否确认删除数据', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning'
      }).then(() => {
        deleteNotice(ids).then(res => {
          if (res.code === '200') {
            _this.$message.success('数据删除成功!');
            _this.searchNotice();
          } else {
            _this.$message.error('数据删除失败：' + res.msg);
          }
        }).catch(err => {
          _this.$router.push('/framework/error')
          console.log('系统出错了!', err);
        })
      }).catch(() => {
        _this.$message.info('用户取消删除!')
        return;
      })
    },
    // 发布
    updateRelease() {
      const _this = this;
      if(_this.tableData.length === 0){
        _this.$message.warning("无数据！")
        return false;
      }
      if(_this.tableData[0].status !== '拟稿'){
        _this.$message.warning("当前无法使用发布功能（已发布或过期）！")
        return false;
      }
      let ids = [];
      if (_this.multipleSelection.length === 0) {
        _this.$message.warning("您未选择数据！")
        return false;
      } else {
        ids = _this.multipleSelection.map(item => item.nuuid);
      }
      // 发送请求
      _this.$confirm('确认是否发布！', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning'
      }).then(() => {
        updateStatus(ids,'1').then(res => {
          if (res.code === '200') {
            _this.$message.success("发布成功!");
            _this.searchNotice();
          } else {
            _this.$message.error('发布失败：' + res.msg);
          }
        }).catch(err => {
          _this.$router.push('/framework/error')
          console.log(err);
        })
      })
    },
    // 编辑公告
    editNotice(row) {
      // 存入数据
      this.rowData = row;
      this.isDialogVisible = true;
      blurElement('nl-assistant-container', 1.5)
      gradeElement('nl-dialog-container', 3)
    },
    // 关闭编辑窗口
    closeEdit() {
      // 关闭公告编辑
      this.isDialogVisible = false;
      blurElement('nl-assistant-container', 0)
      gradeElement('nl-dialog-container', 1)
      this.searchNotice();
    }
  }
}
</script>

<template>
  <div id="nl-main-container" class="nl-main-container">
    <div id="nl-assistant-container" class="nl-assistant-container">
      <div id="nl-one-container" class="nl-one-container">
        <!--批量操作按钮容器-->
        <div id="nl-button-container" class="nl-button-container">
          <el-button @click="deleteNotice(undefined)" type="primary" icon="el-icon-delete" size="small"></el-button>
          <el-button @click="updateRelease" type="primary" size="small">发布<i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </div>
        <!--搜索容器按钮-->
        <div id="nl-search-container" class="nl-search-container">
          <div id="nl-search-select-container">
            <el-select v-model="search.priority" style="width: 90px"
                       slot="prepend" placeholder="优先级" size="small">
              <el-option label="一级" value="1"></el-option>
              <el-option label="二级" value="2"></el-option>
              <el-option label="三级" value="3"></el-option>
              <el-option label="四级" value="4"></el-option>
              <el-option label="五级" value="5"></el-option>
              <el-option label="六级" value="6"></el-option>
            </el-select>
            <el-select v-model="search.type" style="width: 100px"
                       slot="prepend" placeholder="公告类型" size="small">
              <el-option
                v-for="option in types"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
            <el-select v-model="search.status" style="width: 90px"
                       slot="prepend" placeholder="状态" size="small">
              <el-option
                v-for="option in statuses"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </div>
          &nbsp;
          <div id="nl-search-data-container">
            <el-date-picker
              :clearable="false"
              v-model="search.releaseTime"
              type="daterange"
              range-separator="至"
              start-placeholder="发布日期(始)"
              end-placeholder="发布日期(末)"
              size="small"
              style="width:230px">
            </el-date-picker>
          </div>
          &nbsp;
          <div id="nl-search-input-container">
            <el-input placeholder="请输入搜索标题" v-model="search.title" class="input-with-select" style="width: 250px"
                      size="small">
            </el-input>
            <el-button slot="append" icon="el-icon-search" @click="searchNotice" size="small">搜索</el-button>
            <el-button slot="append" icon="el-icon-s-help" @click="clearSearch" size="small">清空</el-button>
          </div>
        </div>
      </div>
      <!--表格容器-->
      <div id="nl-table-container" class="nl-table-container">
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          height="100%"
          @selection-change="handleSelectionChange">
          <!--====================序号====================-->
          <el-table-column
            type="index"
            width="50"
            align="center">
          </el-table-column>
          <!--====================选中====================-->
          <el-table-column
            type="selection"
            align="center"
            width="55">
          </el-table-column>
          <!--====================n_uuid====================-->
          <el-table-column
            prop="nuuid"
            v-if=false>
          </el-table-column>
          <!--====================标题====================-->
          <el-table-column
            prop="title"
            label="标题"
            width="250"
            align="center">
          </el-table-column>
          <!--====================类型====================-->
          <el-table-column
            prop="type"
            label="类型"
            width="100"
            align="center">
          </el-table-column>
          <!--====================优先级====================-->
          <el-table-column
            prop="priority"
            label="优先级(1-->6)"
            width="120"
            align="center">
            <template slot-scope="scope">
              {{ scope.row.priority }}&nbsp;级
            </template>
          </el-table-column>
          <!--====================状态====================-->
          <el-table-column
            prop="status"
            label="状态"
            width="100">
          </el-table-column>
          <!--====================发布日期====================-->
          <el-table-column
            prop="releaseTime"
            label="发布日期"
            width="180">
            <template slot-scope="scope">
              {{ scope.row.status === '拟稿' ? '尚未发布' : formatDate(scope.row.releaseTime) }}
            </template>
          </el-table-column>
          <!--====================截止日期====================-->
          <el-table-column
            prop="deadline"
            label="截止日期"
            width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.deadline) }}
            </template>
          </el-table-column>
          <!--====================内容(隐）====================-->
          <el-table-column
            prop="context"
            v-if=false>
          </el-table-column>
          <!--====================附件(隐）====================-->
          <el-table-column
            prop="annex"
            v-if=false>
          </el-table-column>
          <!--====================更新时间(隐）====================-->
          <el-table-column
            prop="updateTime"
            v-if=false>
          </el-table-column>
          <!--====================操作====================-->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="deleteNotice(scope.row)">删除
              </el-button>
              <el-button
                size="mini"
                @click="editNotice(scope.row)">编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="nl-page-container" class="nl-page-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[5,10,15,20,50]"
          :page-size="search.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNumber">
        </el-pagination>
      </div>
    </div>
    <div id="nl-dialog-container" class="nl-dialog-container">
      <div v-if="isDialogVisible" id="nl-dialog" class="nl-dialog">
        <edit-dialog :rowData="rowData" @closeEdit="closeEdit"></edit-dialog>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import "noticeListCss.css";
</style>
